package com.summer.springboot.mybatisplus.multiple.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 数据源配置
 * @版权:Copyright 2021 版权所有：slinceob
 * @author: slinceob
 * @date
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource primaryDataSource() {
        DataSource primaryDataSource = DataSourceBuilder.create().build();
        DbContextHolder.addDataSource("primary", primaryDataSource);
        return primaryDataSource;
    }

    @Bean(name = "secondDataSource")
    @Qualifier("secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource() {
        DataSource secondDataSource = DataSourceBuilder.create().build();
        DbContextHolder.addDataSource("second", secondDataSource);
        return secondDataSource;
    }

    @Bean(name = "myRoutingDataSource")
    public MyRoutingDataSource dataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource,
                                          @Qualifier("secondDataSource") DataSource secondDataSource) {
        MyRoutingDataSource dynamicDataSource = new MyRoutingDataSource();
        Map<Object, Object> targetDataResources = new HashMap<>();
        targetDataResources.put("primary", primaryDataSource);
        targetDataResources.put("second", secondDataSource);
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(primaryDataSource);
        dynamicDataSource.setTargetDataSources(targetDataResources);
        DbContextHolder.setDefaultDs("primary");
        return dynamicDataSource;
    }

}
